import styles from './styles.less';
import {Pagination, Table, Space, Tag, Modal, Dropdown} from 'antd';
import {useCallback, useEffect, useState} from 'react';
import {DownOutlined, ExclamationCircleFilled} from '@ant-design/icons';
import Opera from './Opera';

import {connect, useAccess} from 'umi';

const DataTable = (props) => {
  const access = useAccess();
  const {dispatch, dataTable, loading, submitting} = props;
  const {users, setDataForm, setResetPassForm, tablePayload, setTablePayload} = props.data;
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    if (!payload.param.mchCode) {
      dispatch({
        type: 'PMchInfoUsers/chgDataTable',
        payload: {total: 0, list: []}
      });
    } else {
      dispatch({
        type: 'PMchInfoUsers/fetchList',
        payload: payload,
      });
    }
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    fetchList({...tablePayload, param: {mchCode: users ? users.data.code : ''}});
  }, [fetchList, tablePayload, users]);

  /* 重置密码 */
  function resetPass(record) {
    setResetPassForm({
      visible: true,
      title: '重置密码',
      data: record,
    });
  }

  /* 编辑 */
  function edit(e, record) {
    e.preventDefault();
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
    return false;
  }

  /* 删除 */
  function del(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定删除数据？',
        onOk() {
          dispatch({
            type: 'PMchInfoUsers/del',
            payload: [record.id],
            callback: () => {
              setTablePayload({...tablePayload, pageNum: 1});
              setSelectedRowKeys([]);
            },
          });
        },
      });
    }
    return false;
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.pageNum - 1) * tablePayload.pageSize + index + 1}
        </span>
      ),
    },
    {
      title: '登录账号',
      dataIndex: 'username',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      render: (_, record) => {
        return (
          <Tag color={record.status === 1 ? 'geekblue' : 'volcano'}>
            {record.status === 1 ? '正常' : '停用'}
          </Tag>
        );
      },
    },
    {
      title: '超级管理员',
      dataIndex: 'root',
      align: 'center',
      width: 100,
      render: (_, record) => {
        return (
          <Tag color={record.root === 1 ? 'geekblue' : 'volcano'}>
            {record.root === 1 ? '是' : '否'}
          </Tag>
        );
      },
    },
    {
      title: '退款权限',
      dataIndex: 'refund',
      align: 'center',
      width: 100,
      render: (_, record) => {
        return (
          <Tag color={record.refund === 1 ? 'geekblue' : 'volcano'}>
            {record.refund === 1 ? '是' : '否'}
          </Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      render: (_, record) => {
        let items = [];
        if (access?.mch_user_resetPass) {
          items = [...items, {key: 'resetPass', label: '重置密码', onClick: () => resetPass(record)}];
        }
        return (
          <Space size='small'>
            {(access?.mch_user_edit) && (
              <a onClick={e => edit(e, record)}>编辑</a>
            )}
            {(access?.mch_user_del) && (
              <a onClick={e => del(e, record)}>删除</a>
            )}
            {(items.length > 0) && (
              <Dropdown arrow menu={{items}}>
                <a onClick={(e) => e.preventDefault()}>
                  更多<DownOutlined/>
                </a>
              </Dropdown>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <div className={styles.myDataTable}>
        <Opera data={{users, setDataForm, selectedRowKeys, setSelectedRowKeys, tablePayload, setTablePayload}}/>
        <Table
          rowSelection={{
            selectedRowKeys,
            onChange: (newSelectedRowKeys) => setSelectedRowKeys(newSelectedRowKeys),
          }}
          className={styles.myTable} bordered={false} size={'middle'} columns={columns}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{y: '100%'}} loading={loading}
        />
      </div>
      <Pagination
        pageSize={tablePayload.pageSize} current={tablePayload.pageNum} total={dataTable.total}
        className={styles.myPagination} size={'default'} hideOnSinglePage={false}
        showTotal={(total) => {
          return `共 ${total} 条记录`;
        }}
        pageSizeOptions={[10, 30, 60, 120]}
        showSizeChanger showQuickJumper={true}
        onChange={(page, pageSize) => {
          setTablePayload({...tablePayload, pageNum: page, pageSize: pageSize});
        }}
      />
    </>

  );
};

export default connect(({loading, PMchInfoUsers}) => {
  return {
    loading: loading.effects['PMchInfoUsers/fetchList'],
    submitting: loading.effects['PMchInfoUsers/del'],
    dataTable: PMchInfoUsers.dataTable,
  };
})(DataTable);
